package com.easyj.base.security.service;

import java.io.IOException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Service;

import com.easyj.admin.db.model.User;
import com.easyj.admin.sys.service.UserService;
import com.easyj.base.common.ajax.Result;
import com.easyj.base.security.SecurityConstant;
import com.easyj.base.util.RemoteAddressUtil;
import com.fasterxml.jackson.databind.ObjectMapper;

@Service
public class DefaultAuthenticationFailureHandler implements AuthenticationFailureHandler{
	@Autowired
	private ObjectMapper objectMapper;
   
	@Autowired
	private UserService userService;
	
	@Override
	public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
			AuthenticationException exception) throws IOException, ServletException {
		
		String message;
		if(exception instanceof UsernameNotFoundException) {
			 message="无效的账号或密码！连续"+SecurityConstant.Max_ErrCount+"次密码错误，账号将被锁定。";
		}
		else if(exception instanceof BadCredentialsException) {
			if(request.getAttribute("user_id" )==null) {
				message="无效的账号或密码！连续"+SecurityConstant.Max_ErrCount+"次密码错误，账号将被锁定。";
			}else {
				Integer errcount=(Integer)request.getAttribute("login_errcount")+1;
				if(errcount>SecurityConstant.Max_ErrCount) {
					message="连续"+SecurityConstant.Max_ErrCount+"次密码错误，账号被锁定。";
					lockedUser(request);
				}else {
				  updateLoginInfo(request);
				  message="无效的账号或密码！连续"+SecurityConstant.Max_ErrCount+"次密码错误，账号将被锁定。";
				}
			}	
			
		}else if(exception instanceof LockedException) {
			message="账号已被锁定！";
		} else {
        	message="登录失败！";
        }
			
		Result result=Result.Error(message);
		String json = objectMapper.writeValueAsString(result);
	    response.setContentType("application/json;charset=UTF-8");
	    response.getWriter().write(json);
		
	}

	private void updateLoginInfo(HttpServletRequest request) {
		try {
			if(request.getAttribute("user_id" )!=null) {
				User user=new User();
				user.setId((Long)request.getAttribute("user_id"));
				user.setLoginSuccess(false);
				user.setLoginErrCount((Integer)request.getAttribute("login_errcount")+1);//失败次数
				user.setLoginIp(RemoteAddressUtil.getIp(request));
				user.setLoginTime(new Date());
				userService.saveLoginInfo(user);
			}
		}catch(Exception ex) {
			//ex.printStackTrace();
		}
	}
	
	private void lockedUser(HttpServletRequest request) {
		try {
			if(request.getAttribute("user_id" )!=null) {				
				userService.lockedUserById((Long)request.getAttribute("user_id"));
			}
		}catch(Exception ex) {
			//ex.printStackTrace();
		}
	}
}
